博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Struts2学习(三)
阅读量:5269 次
发布时间:2019-06-14

本文共 10057 字,大约阅读时间需要 33 分钟。

获取页面数据

1、属性驱动

  • 对于属性驱动,我们需要在Action中定义与表单元素对应的所有的属性,因而在Action中会出现很多的getter和setter方法
  • 表单 或 URL 中的 参数名称 跟 Action 类中的属性名称一致,即可
  • 属性驱动的第一种方式(推荐使用的方式,直接将action做一个model(类似bean结构),就可以得到请求参数.)

    index.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    Apache Struts   

    属性驱动(赞成使用):

    注册

    struts.xml

    /WEB-INF/pages/results/register_success.jsp
    /WEB-INF/pages/results/login_success.jsp

    Action类

    package ecut.results.action;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import com.opensymphony.xwork2.Action;import ecut.results.entity.Customer;public class RegisterAction implements Action {        private static final Logger logger = LogManager.getLogger();        private String username ;    private String password ;    private String confirm ;        private Customer customer ;    @Override    public String execute() throws Exception {                if( customer != null ) {            logger.info( "customer username : " + customer.getUsername() );            logger.info( "customer password : " + customer.getPassword() );            logger.info( "customer confirm : " + customer.getConfirm() );        } else {            logger.info( "username : " + username );            logger.info( "password : " + password );            logger.info( "confirm : " + confirm );        }                return SUCCESS;    }    public Customer getCustomer() {        return customer;    }    public void setCustomer(Customer customer) {        this.customer = customer;    }        public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getConfirm() {        return confirm;    }    public void setConfirm(String confirm) {        this.confirm = confirm;    }    }

    register_success.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    注册成功

    注册成功

    username: ${ username }

    page scope: ${ pageScope.username }

    request scope: ${ requestScope.username }

    session scope: ${ sessionScope.username }

    application scope: ${ applicationScope.username }


    customer.username : ${ customer.username }

    request scope: ${ requestScope.customer.username }

    在同一个请求中因此参数保留在requestScope中

  • 属性驱动的第二种方式(反对使用,在action中声明一个model,js不通用)

    index.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    Apache Struts   

    属性驱动(反对使用):

    Action中增加customer 的model

2、模块驱动

  •  对于模型驱动,使用的Action对象需要实现ModelDriven接口并给定所需要的类型.而在Action中我们只需要定义一个封装所有数据信息的javabean
  • 模块驱动的具体实现

    index.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    Apache Struts  

    模型驱动:

    Action类

    package ecut.results.action;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ModelDriven;import ecut.results.entity.Customer;public class LoginAction implements Action , ModelDriven
    { private static final Logger logger = LogManager.getLogger(); private Customer customer ; @Override public String execute() throws Exception { System.out.println( this ); logger.info( "username : " + customer.getUsername() ); logger.info( "password : " + customer.getPassword() ); return SUCCESS; } @Override public Customer getModel() { logger.info( "调用 getModel方法" ); //首先实现接口ModelDriven,其次通过getModel方法告诉Struts将参数封装到那个对象去 if( this.customer == null ) { logger.info( "创建对象" ); this.customer = new Customer(); } return this.customer ; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; }}

    Action类实现ModelDriven接口并覆盖getModel()方法,在Action类中实例化一个model对象,由Struts2提供的拦截器(ParametersInterceptor)去完成数据封装,让getModel方法返回这个对象。getModel()方法在excute()方法执行之前。因为每一次请求,都是一个新的action,所以getModel()方法中的判断语句是多余的,与spring有所不同。

    注意:getModel 返回的是Action类中定义的model(this.customer),而不能直接返回 new Customer,excute方法和getModel应该使用的是同一个对象,不然会抛出空指针异常

    login_success.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    登录成功

    登录成功

    customer.username : ${ customer.username }

    request scope: ${ requestScope.customer.username }


    session scope: ${ sessionScope.customer.username }

访问 Servlet API

1、间接访问(推荐使用的方法)
  • 通过ActionContext来访问
    ActionContext context = ActionContext.getContext();
    Map<String,Object> applicationMap = context.getApplication(); // 这个 Map 集合 ServletCotnext
    Map<String,Object> sessionMap = context.getSession(); // 这个 Map 集合与 HttpSession
    HttpParameters params = context.getParameters(); // request parameter
  • 测试案例

    index.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    Apache Struts

    登录( 并将用户信息存储到 Session 中 ):

    ${ sessionScope.error_message } <%--EL3.0才支持直接调用方法 ${ pageContext.session.removeAttribute( 'error_message' ) } --%>
    <% session.removeAttribute( "error_message" ) ;%>

     struts.xml

      
    main
    /results/index.jsp
    /WEB-INF/pages/results/login_success.jsp
    /results/index.jsp

    Action类

    package ecut.results.action;import java.util.Map;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ModelDriven;import ecut.results.entity.Customer;public class CustomerAction implements Action , ModelDriven
    { private Customer customer ; @Override public String execute() throws Exception { System.out.println( "execute" ); return SUCCESS; } public String login() throws Exception { System.out.println( "login" ); // 获得 当前正在执行的 Action 的 上下文对象 ActionContext context = ActionContext.getContext(); // 通过 ActionContext 的 getSession 来获得 与 HttpSession 对应的 Map 集合 // 针对这个 Map 的 所有操作 都会立即 "同步" 到 HttpSession 对象中 Map< String , Object > sessionMap = context.getSession(); if( "zhangsanfeng".equals( customer.getUsername() ) && "hello2017".equals( customer.getPassword() ) ){ sessionMap.put( "customer" , this.customer ) ; // 由拦截器去完成这个操作session.setAttribute( "customer" , this.customer ); return SUCCESS; } else { sessionMap.put( "error_message" , "用户名或密码错误" ); return INPUT; } } public String logout() throws Exception { System.out.println( "logout" ); ActionContext context = ActionContext.getContext(); Map< String , Object > sessionMap = context.getSession(); sessionMap.remove( "customer" ) ; // session.removeAttribute( "customer" ); return SUCCESS; } @Override public Customer getModel() { if( this.customer == null ){ this.customer = new Customer(); } return this.customer; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }

    login_success.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    登录成功

    登录成功

    customer.username : ${ customer.username }

    request scope: ${ requestScope.customer.username }


    session scope: ${ sessionScope.customer.username }

    注销

    logout_success.jsp

    <%@ page language = "java" pageEncoding = "UTF-8" %> <%@ page contentType = "text/html; charset= UTF-8"%>
    注销成功

    注销成功

2、直接访问(不推荐使用,如果已经使用了 Struts 框架,则应该优先考虑使用 Struts 而不是使用 Servlet )
  • 实现接口并提供 setter 方法(与servlet API 耦合大).
    org.apache.struts2.util.ServletContextAware
    org.apache.struts2.interceptor.ServletRequestAware
    org.apache.struts2.interceptor.ServletResponseAware
  • 通过 ServletActionContext 类的静态方法
    org.apache.struts2.ServletActionContext.getPageContext()
    org.apache.struts2.ServletActionContext.getRequest()
    org.apache.struts2.ServletActionContext.getRequest().getSession()
    org.apache.struts2.ServletActionContext.getResponse()
    org.apache.struts2.ServletActionContext.getServletContext()

转载请于明显处标明出处

转载于:https://www.cnblogs.com/AmyZheng/p/9204047.html

你可能感兴趣的文章
python第一课————软件安装及“hello,world”程序编写
查看>>
面试汇总,每次的面试,都会使我更进一步。
查看>>
Oracle 查询用户和删除用户
查看>>
SilverLight之旅(3)
查看>>
若有恒,何必三更眠五更起;最无益,莫过一日曝十日寒
查看>>
[na]office 2010 2013卸载工具
查看>>
OpenFlow Switch
查看>>
Redis笔记-Sentinel哨兵模式
查看>>
java 多线程
查看>>
分布式Redis深度历险-Sentinel
查看>>
用移动硬盘装windows 7时 遇到 A required CD/DVD device driver is missing 的问题
查看>>
leetcode 51 N-Queens & 52 N-Queens II ----- java
查看>>
图片上传
查看>>
死锁及oracle死锁--转载
查看>>
Android设置监听
查看>>
findByExample(Object exampleEntity)方法得到的List判断是否为空,不可用(lis != null)
查看>>
pip下载保存Python包,pip离线安装
查看>>
mysql建库建表
查看>>
实验五
查看>>
spark生成大宽表的parquet性能优化
查看>>